import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { useTimeSettingStore } from "@/store";
import type { TimeSettingFormData } from "@/api/hmi/time-setting.api";
import { useErrorHandler } from "@/composables/useErrorHandler";

/**
 * 时间设置 Composable
 */
export function useTimeSetting() {
  // Store
  const timeSettingStore = useTimeSettingStore();
  
  // 错误处理
  const { handleError, withErrorHandling } = useErrorHandler();

  // 本地状态
  const localTimeSetting = ref<TimeSettingFormData>({
    zone: 8,
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),
    hour: new Date().getHours(),
    minute: new Date().getMinutes(),
    sec: new Date().getSeconds(),
  });

  const refreshing = ref<boolean>(false);
  const updating = ref<boolean>(false);

  // 计算属性
  const isLoading = computed(() => timeSettingStore.isLoading || refreshing.value);
  const isUpdating = computed(() => timeSettingStore.isUpdating || updating.value);
  const isReady = computed(() => timeSettingStore.isReady);
  const currentTimeSetting = computed(() => timeSettingStore.currentTimeSetting);

  /**
   * 初始化时间设置
   * @param cpu CPU 编号
   */
  const initTimeSetting = async (cpu: number = 1) => {
    const result = await withErrorHandling(
      () => timeSettingStore.fetchTimeSetting(cpu),
      "初始化时间设置",
      { showMessage: false }
    );

    if (result) {
      syncLocalTimeSetting();
    }
  };

  /**
   * 刷新时间设置
   * @param cpu CPU 编号
   */
  const refreshTimeSetting = async (cpu: number = 1) => {
    refreshing.value = true;
    
    try {
      await timeSettingStore.fetchTimeSetting(cpu);
      syncLocalTimeSetting();
      ElMessage.success("时间设置刷新成功");
    } catch (error: any) {
      handleError(error, "刷新时间设置");
    } finally {
      refreshing.value = false;
    }
  };

  /**
   * 更新时间设置
   * @param cpu CPU 编号
   * @param timeSettingData 时间设置数据
   */
  const updateTimeSetting = async (
    cpu: number = 1, 
    timeSettingData?: TimeSettingFormData
  ) => {
    const dataToUpdate = timeSettingData || localTimeSetting.value;
    
    // 验证数据
    const validation = timeSettingStore.validateTimeSetting(dataToUpdate);
    if (!validation.isValid) {
      ElMessage.error(`数据验证失败：${validation.errors.join(", ")}`);
      return false;
    }

    updating.value = true;

    try {
      const result = await timeSettingStore.updateTimeSetting(cpu, dataToUpdate);
      
      if ('status' in result && result.status === 'success') {
        ElMessage.success("时间设置更新成功");
        syncLocalTimeSetting();
        return true;
      } else if ('error' in result) {
        ElMessage.error(`时间设置更新失败：${result.message || result.error}`);
        return false;
      }
      
      return true;
    } catch (error: any) {
      handleError(error, "更新时间设置");
      return false;
    } finally {
      updating.value = false;
    }
  };

  /**
   * 同步本地时间设置
   */
  const syncLocalTimeSetting = () => {
    const currentSetting = timeSettingStore.getCurrentTimeSetting();
    localTimeSetting.value = { ...currentSetting };
  };

  /**
   * 重置本地时间设置
   */
  const resetLocalTimeSetting = () => {
    syncLocalTimeSetting();
  };

  /**
   * 设置当前时间
   */
  const setCurrentTime = () => {
    const now = new Date();
    localTimeSetting.value = {
      ...localTimeSetting.value,
      year: now.getFullYear(),
      month: now.getMonth() + 1,
      day: now.getDate(),
      hour: now.getHours(),
      minute: now.getMinutes(),
      sec: now.getSeconds(),
    };
  };

  /**
   * 验证时间设置数据
   * @param timeSettingData 时间设置数据
   */
  const validateTimeSetting = (timeSettingData?: TimeSettingFormData) => {
    const dataToValidate = timeSettingData || localTimeSetting.value;
    return timeSettingStore.validateTimeSetting(dataToValidate);
  };

  /**
   * 格式化时间显示
   * @param timeSettingData 时间设置数据
   */
  const formatTimeDisplay = (timeSettingData?: TimeSettingFormData): string => {
    const data = timeSettingData || localTimeSetting.value;
    const zoneStr = data.zone >= 0 ? `+${data.zone}` : `${data.zone}`;
    return `${data.year}-${String(data.month).padStart(2, '0')}-${String(data.day).padStart(2, '0')} ` +
           `${String(data.hour).padStart(2, '0')}:${String(data.minute).padStart(2, '0')}:${String(data.sec).padStart(2, '0')} ` +
           `(UTC${zoneStr})`;
  };

  /**
   * 获取时区选项
   */
  const getTimezoneOptions = () => {
    const options = [];
    for (let i = -12; i <= 12; i++) {
      const label = i >= 0 ? `UTC+${i}` : `UTC${i}`;
      options.push({ value: i, label });
    }
    return options;
  };

  /**
   * 获取月份天数
   * @param year 年份
   * @param month 月份
   */
  const getDaysInMonth = (year: number, month: number): number => {
    return new Date(year, month, 0).getDate();
  };

  /**
   * 验证日期是否有效
   * @param year 年份
   * @param month 月份
   * @param day 日期
   */
  const isValidDate = (year: number, month: number, day: number): boolean => {
    const maxDays = getDaysInMonth(year, month);
    return day >= 1 && day <= maxDays;
  };

  /**
   * 清理资源
   */
  const cleanup = () => {
    timeSettingStore.resetTimeSettingState();
    refreshing.value = false;
    updating.value = false;
  };

  return {
    // 状态
    localTimeSetting,
    isLoading,
    isUpdating,
    isReady,
    currentTimeSetting,
    refreshing,
    updating,

    // 方法
    initTimeSetting,
    refreshTimeSetting,
    updateTimeSetting,
    syncLocalTimeSetting,
    resetLocalTimeSetting,
    setCurrentTime,
    validateTimeSetting,
    formatTimeDisplay,
    getTimezoneOptions,
    getDaysInMonth,
    isValidDate,
    cleanup,
  };
}
